#include <stdio.h>
#include "tokens.h"
#include "parser.h"
#include "mybc.h"

/** Topdown recursive parser
 * 
 * requires an LL(1) normalized grammar:
 * 
 * E -> [-] T { [+|-] T}
 * T -> F { ['*'|'/'] F}
 * F -> NUM | ID [= E] | '('E')'
 */

void
E(void)
{
  int negate = 0, oplus;
  if(negate = (lookahead == '-')){match('-');}
  T();{/** */negate && printf(" - ");}
  while(lookahead == '+' || lookahead == '-') {
    match(oplus = lookahead);
    T();{/** */printf(" %c ", oplus);}
  }
}


void
T(void)
{
    F();
    while(lookahead == '*' || lookahead == '/') {
      int otimes = lookahead;
      match(lookahead);
      F();{/** */printf(" %c ", otimes);}
    }
}

void
F(void)
{
  switch (lookahead) {
    case NUM:
      {/** */printf(" %lg ", lexval);}
      match(NUM); 
      break;

    case ID:
      {/** */printf(" %s ", lexeme);}
      match(ID);
      if(lookahead == '='){
        match('='); E();{/** */printf(" = ");}
      }
      break;
    
    default:
      match('(');
      E();
      match(')');
}
}
